import { ObjectCopier } from './../../../common/objectCopier';
import { MdDialog, MdDialogRef, MdDialogConfig } from '@angular/material';
import { Component } from '@angular/core';

export class BatchInvtService {
    static current: BatchInvtService = new BatchInvtService();
    private batchInvt: BatchOperateInvtDialog;
    dialogRef: MdDialogRef<BatchOperateInvtDialog>;
    config: MdDialogConfig = {
        disableClose: false,
        width: '100%',
        height: '100%',
        position: {
            top: '0',
            bottom: '0',
            left: '0',
            right: '0'
        }
    }

    regist(batchInvt: BatchOperateInvtDialog) {
        this.batchInvt = batchInvt;
    }

    open(dialog: MdDialog, inventories, preOrderList) {
        this.dialogRef = dialog.open(BatchOperateInvtDialog, this.config);
        inventories = this.filterInvt(inventories);
        this.batchInvt.inventories = <any>ObjectCopier.Copy(inventories);
        this.batchInvt.preOrderList = preOrderList;
        return new Promise((resolve, reject) => {
            this.dialogRef.afterClosed().subscribe((data) => {
                this.dialogRef = null;
                resolve(data);
            })
        })
    }

    /**
     * 过滤掉不需要显示的商品
     * @param inventories 需要过滤的商品数组
     */
    filterInvt(inventories) {
        let result = [];
        if (inventories && inventories.length) {
            result = inventories.filter(invt => {
                let result = this.filterConditions(invt);
                return result;
            });
        }
        return result;
    }

    /**
     * 过滤条件
     * @param invt 需要判断的是否符合显示条件的商品 
     */
    filterConditions(invt): boolean {
        if (invt.inventory && invt.inventory.code == "tablefee") {
            return false;
        }
        return true;
    }


}

@Component({
    selector: 'div[batch-invt]',
    template: `
        <md-dialog-content class="h100" fxLayout="column">
            <header tabindex="0" autofocus class="app-header noshrink">
                <span id="dialog-back-btn" class="i-arrow-back margin-l header-icon" (click)="cancel()"></span>
                <span fxFlex="100%" class="margin-l-xs">上菜</span>
            </header>
            <div fxLayout="column" class="text-s" fxFlex="100%">
                <div class="padding-xs noshrink color-lightgray" fxLayout="row">
                    <md-checkbox [disableRipple]="true" (change)="selectAll($event)" [checked]="checkIsSelectAll()"></md-checkbox>
                    <span class="margin-l-xs">选择全部</span>
                </div>
                <div class="v-scroll" fxFlex="100%">
                    <div class="padding-xs" fxLayout="row" fxLayoutAlign="start center" *ngFor="let invt of inventories">
                        <md-checkbox [disableRipple]="true" [checked]="invt.selected" (change)="selectInvt($event, invt)"></md-checkbox>
                        <span class="margin-l-xs" fxFlex="100%">{{invt.inventoryName}}</span>
                        <div fxLayout="row" fxLayoutAlign="start center">
                            <div class="icon-minus-circle-o batch-btn color-lightgray margin-r-s" (click)="minusBatchQty(invt)"></div>
                            <div fxLayout="row" fxLayoutAlign="center center" class="noshrink batch-qty margin-r-s">
                                <span>{{invt.batchQty ? invt.batchQty : 1}}</span>
                            </div>
                            <div class="i-add-circle color-primary batch-btn margin-r-s" (click)="addBatchQty(invt)"></div>
                        </div>
                    </div>
                </div>
            </div>
            <button md-button class="color-white bgcolor-primary normal-btn text-m noshrink" (click)="confirm()">
                <span>确定</span>
            </button>
        </md-dialog-content>
    `,
    styleUrls: ['../tableDetail.component.scss']
})
export class BatchOperateInvtDialog {
    constructor(
        private dialogRef: MdDialogRef<BatchOperateInvtDialog>
    ) {
        BatchInvtService.current.regist(this);
    }
    inventories = [];
    preOrderList = []
    /**
     * 检查是否全选
     */
    checkIsSelectAll() {
        if (!this.inventories || !this.inventories.length) {
            return false;
        }
        let invt = this.inventories.find((item) => {
            return !item.selected;
        });
        if (invt) {
            return false;
        } else {
            return true;
        }
    }
    /**
     * 商品数量减1
     * @param invt 
     */
    minusBatchQty(invt) {
        let refundQty = invt.refundQty ? invt.refundQty : 0;
        let dishupQty = (invt.extended && invt.extended.dishup) ? invt.extended.dishup.qty : 0;
        let maxQty = invt.qty - refundQty - dishupQty;
        let batchQty = invt.batchQty ? invt.batchQty : 1;
        if (batchQty > 1) {
            batchQty--;
            invt.batchQty = batchQty;
        } else {

        }
    }
    /**
     * 商品数量加1
     * @param invt 
     */
    addBatchQty(invt) {
        let refundQty = invt.refundQty ? invt.refundQty : 0;
        let dishupQty = (invt.extended && invt.extended.dishup) ? invt.extended.dishup.qty : 0;
        let maxQty = invt.qty - refundQty - dishupQty;
        let batchQty = invt.batchQty ? invt.batchQty : 1;
        if (batchQty < maxQty) {
            batchQty++;
            invt.batchQty = batchQty;
        } else {

        }
    }
    /**
     * 全选
     */
    selectAll(event) {
        this.inventories.forEach((item) => {
            item.selected = event.checked;
        })
    }
    selectInvt(event, invt) {
        invt.selected = event.checked;
    }
    /**
     * 获得选中的商品信息
     */
    getSelectedInvts() {
        let result = [];
        let selectInvts = this.inventories.filter((invt) => {
            return invt.selected;
        });
        if (selectInvts && selectInvts.length) {
            try {
                selectInvts.forEach((item) => {
                    let invtDomain: any = {};
                    let preOrderId = this.getPreorderIdByCartId(item.id);
                    invtDomain.invertoryId = item.inventoryId;
                    invtDomain.count = item.batchQty ? item.batchQty : 1;
                    invtDomain.cartItemId = item.id;
                    invtDomain.orderId = preOrderId;
                    result.push(invtDomain);
                });
            } catch (error) {
                console.log(error);
            }
        }
        return result;
    }
    /**
     * 通过购物车id获取preOrder的id
     * @param cartId 
     */
    getPreorderIdByCartId(cartId: string) {
        let result = null;
        if (this.preOrderList && this.preOrderList.length) {
            for (let preOrder of this.preOrderList) {
                let targetPreOrder = preOrder.cart.items.find((cartItem) => {
                    return cartItem.id == cartId;
                });
                if (targetPreOrder) {
                    result = preOrder.id;
                    break;
                }
            }
        }
        if (!result) {
            throw new Error("未找到购物车项对应的preOrder的id");
        }
        return result;
    }

    confirm() {
        let result = this.getSelectedInvts();
        this.dialogRef.close(result);
    }

    cancel() {
        this.dialogRef.close(null);
    }
}